# models.py
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

db = SQLAlchemy()

class WebhookEvent(db.Model):
    __tablename__ = 'webhook_events'
    id = db.Column(db.Integer, primary_key=True)
    repository_name = db.Column(db.String(255), nullable=False)
    repository_owner = db.Column(db.String(255), nullable=False)
    pusher = db.Column(db.String(255), nullable=False)
    ref = db.Column(db.String(255), nullable=False)
    before_sha = db.Column(db.String(40), nullable=False)
    after_sha = db.Column(db.String(40), nullable=False)
    received_at = db.Column(db.DateTime, default=datetime.utcnow)

    invalid_commits = db.relationship('InvalidCommit', backref='event', lazy=True)

    def __repr__(self):
        return f'<WebhookEvent {self.id} - {self.repository_owner}/{self.repository_name}>'

class InvalidCommit(db.Model):
    __tablename__ = 'invalid_commits'
    id = db.Column(db.Integer, primary_key=True)
    sha = db.Column(db.String(40), nullable=False)
    author = db.Column(db.String(255), nullable=False)
    message = db.Column(db.Text, nullable=False)
    url = db.Column(db.String(255), nullable=False)
    detected_at = db.Column(db.DateTime, default=datetime.utcnow)
    event_id = db.Column(db.Integer, db.ForeignKey('webhook_events.id'), nullable=False)

    def __repr__(self):
        return f'<InvalidCommit {self.sha} by {self.author}>'
